#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>
int main()
{
	char line[100];
	int flag = 100;
	char *temp;
	char *word[10];
	int c;
	pid_t pid;
	while (1)
	{
		int numm = 0;
		printf("> ");
		int num = 1;
		fgets(line, sizeof(line), stdin);
		line[strlen(line) - 1] = '\0';
		temp = strtok(line, " ");
		word[0] = temp;
		while (temp != NULL)
		{
			temp = strtok(NULL, " ");
			word[num] = temp;
			num++;
		}
		word[num] = NULL;

		char a[100];
		int mm = 0;
		// printf("%d\n",num);
		//	printf("%s\n",word[num-2]);
		for (int i = 0; word[num - 2][i] != '\0'; i++)
		{
			if (word[num - 2][i] == '>' || word[num - 2][i] == '<')
			{
				numm++;
				continue;
			}
			a[mm] = word[num - 2][i];
			mm++;
		}
		a[mm] = '\0';
		if (numm == 2)
			word[num - 2] = NULL;
		// printf("%s\n",a);
		// printf("%d\n",numm);
		pid = fork();
		// printf("here");

		if (pid == -1)
		{
			perror("can not open a precedure!");
			exit(1);
		}
		else if (pid == 0)
		{
			if (numm == 1 && word[num - 2][0] == '>')
			{
				int fd = open(a, O_WRONLY | O_CREAT | O_TRUNC);
				// printf("here here ");
				dup2(fd, 1);
				close(fd);
				word[num - 2] = NULL;
				execvp(word[0], word);
				dup2(1, 1);
			}
			else if (numm == 1 && word[num - 2][0] == '<')
			{
				int fd = open(a, O_RDONLY);
				if (fd == -1)
				{
					perror("can not open this file");
					exit(1);
				}
				dup2(fd, 0);
				close(fd);
				word[num - 2] = NULL;
				execvp(word[0], word);
				dup2(0, 0);
			}
			else if (numm == 2)
			{
				int fd = open(a, O_APPEND);
				if (fd == -1)
				{
					perror("can not open this file");
					exit(1);
				}
				dup2(fd, 1);
				word[num - 2] = NULL;
				execvp(word[0], word);
				close(fd);
				dup2(1, 1);
			}
			else
			{
				execvp(word[0], word);
			}
			exit(0);
		}
		else
		{
			wait(NULL);
		}

		if (strcmp(word[0], "exit") == 0)
			exit(0);
	}
	return 0;
}
